#include "CPanelDashboard.h"

#include <QHBoxLayout>
#include <QPushButton>
#include <QStackedWidget>

#include "core/CDeviceManager.h"
#include "core/logger.h"
#include "view/component/dashboard/CDashboard_DCB.h"
#include "view/component/dashboard/CDashboard_MCB.h"
#include "view/component/dashboard/CDashboard_TCB.h"

CPanelDashboard::CPanelDashboard(QWidget* parent) :
    CPanelWidget(parent),
    dashboards_(new QStackedWidget(this))
{
    // layout
    auto lay = new QHBoxLayout;
    lay->addWidget(dashboards_);
    lay->setSpacing(0);
    lay->setMargin(0);
    getContent()->setLayout(lay);
    getHeaderButton(0)->hide();
    getHeaderButton(1)->hide();
    setWindowTitle("");

    // dashboards
    dashboards_->insertWidget(0, new QWidget);

    // default
    eventDeviceChanged("");
}

CPanelDashboard::~CPanelDashboard()
{
}

void CPanelDashboard::setDeviceConfig(const ZLDeviceConfig& config)
{
    // 移除之前的所有窗口
    for (int i = 1; i < dashboards_->count(); ++i)
    {
        dashboards_->removeWidget(dashboards_->widget(i));
    }

    // 根据设备列表添加窗口
    for (const auto& d : config.zlbase_info.devices)
    {
        QWidget* wnd = nullptr;
        switch (d.type)
        {
            case zl::zlbase::EDeviceType_DCB:
                wnd = new CDashboard_DCB;
                break;
            case zl::zlbase::EDeviceType_MCB:
                wnd = new CDashboard_MCB;
                break;
            case zl::zlbase::EDeviceType_TCB:
                wnd = new CDashboard_TCB;
                break;
            default:
                break;
        }

        if (wnd == nullptr) return;
        wnd->setProperty("deviceid", d.id.c_str());
        wnd->setWindowTitle(tr("Current Device: %1 @ %2").arg(d.name.c_str()).arg(d.number));
        dashboards_->insertWidget(dashboards_->currentIndex() + 1, wnd);
    }

    // 添加外设控制窗口

    // 设置默认显示窗口
    dashboards_->setCurrentIndex(0);
}

void CPanelDashboard::eventDeviceChanged(QString id)
{
    // 查找当前选中的窗口
    for (int i = 1; i < dashboards_->count(); ++i)
    {
        auto wnd = dashboards_->widget(i);
        if (wnd->property("deviceid").toString() == id)
        {
            // todo
            setWindowTitle(wnd->windowTitle());
            dashboards_->setCurrentIndex(i);
            return;
        }
    }

    // 未找到匹配的窗口
    setWindowTitle(tr("Dashboard - No Device Selected"));
    dashboards_->setCurrentIndex(0);
}